package com.cdty.chess.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.cdty.chess.model.Cuser;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Calendar;
import java.util.Date;

@Component
public class TokenUtils {

    public static final String SECRET = "chess@2025"; // 系统固定密钥

    /**
     * 生成token
     *
     * @return
     */
    public static String genToken(String userId,String jti ) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY,12);
        Date time = calendar.getTime();
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withClaim("jti",jti)
                .withExpiresAt(time) // 2小时后token过期
                .sign(Algorithm.HMAC256(SECRET)); // 密钥
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
    public static Cuser getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.hasText(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                //return staticUserMapper.selectById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}